package com.atguigu.gulimall.search.service.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to_and_vo.es.SkuEsModel;
import com.atguigu.gulimall.search.config.GulimallElasticConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.Index;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    //商品的上架功能
    @Override
    public boolean productStatusUp(List<SkuEsModel> upProducts) throws IOException {
        //将数据保存到ES中
        //1.给ES建立一个索引,将索引名抽取为一个常量，放在com.atguigu.gulimall.search.constant.EsConstant中
            //  我们通过kibana已经操作好了
        //2.给ES中保存数据
        //bulk(BulkRequest bulkRequest, RequestOptions options)
        BulkRequest bulkRequest = new BulkRequest();
        //构造保存请求，并放入bulkRequest中
        for (SkuEsModel model : upProducts) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(model.getSkuId().toString());
            String s = JSON.toJSONString(model);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticConfig.COMMON_OPTIONS);

        //TODO 如果批量存储出现错误：
        boolean b = bulk.hasFailures();
        String s = bulk.buildFailureMessage();
        List<String> collect = Arrays.stream(bulk.getItems()).map((item) -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.info("商品上架完成：{},返回数据: ",collect,bulk.toString());

        return b;
    }
}
